package ssm.Test;

import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.transaction.annotation.Transactional;
import ssm.Dao.SurplusDao;
import ssm.Dao.UserDao;
import ssm.Pojo.YzUsers;

import java.text.DecimalFormat;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Semaphore;

/**
 * @Author Maple.Chen
 * @Description
 * @Date 15:44 2020/3/23
 **/
@Transactional
public class Thread1 implements Runnable{
    private final Semaphore parallel = new Semaphore(10);

    private static Integer aaa=1;  // 定义一个线程共享变量

    private UserDao ud;
    private SurplusDao spd;
    private List<YzUsers> list;
    private static SqlSessionFactory sqlSessionFactory;

    public Thread1(List<YzUsers> list,UserDao ud,SurplusDao spd,SqlSessionFactory sqlSessionFactory){
        this.list = list;
        this.ud=ud;
        this.spd=spd;
        this.sqlSessionFactory=sqlSessionFactory;
    }

    @Override
    public void run() {
        synchronized(this){
            try {
                parallel.acquire();
                insert();
                System.out.println("当前剩余通道数="+parallel.availablePermits());
                parallel.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void insert(){
        Map<String,Object> mmp=new LinkedHashMap<>();
        mmp.put("status",new Random().nextInt(12)+1); //[1,12)+1
        mmp.put("userlist",list);
        ud.BatchInsertUsers(mmp);
        // 初始化余额，保留两位小数
        Map<String,Object> map=new LinkedHashMap<>();
        DecimalFormat df = new DecimalFormat("######0.00");
        for(YzUsers u:list){
            map.put(u.getId(),df.format(Math.random()*50)+1);
        }
        spd.BatchInit(map);
        System.out.println("Thread-" + (aaa++));
    }

}
